#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pandas as pd
import re

def analyze_carrier_sections(file_path, sheet_name='FS045W'):
    """分析Excel文件中的运营商分组"""
    print(f"正在分析 {sheet_name} 工作表的运营商分组...")
    
    # 读取Excel文件，不设置header，以便分析原始结构
    df = pd.read_excel(file_path, sheet_name=sheet_name, header=None)
    
    print(f"数据形状: {df.shape}")
    
    carriers = []
    current_carrier = None
    
    # 遍历每一行查找运营商信息
    for index, row in df.iterrows():
        # 检查是否包含PLMN信息（运营商标识行）
        row_str = ' '.join([str(cell) for cell in row if pd.notna(cell)])
        
        if 'PLMN' in row_str:
            # 提取运营商名称和PLMN代码
            plmn_match = re.search(r'PLMN\s*(\d+)', row_str)
            plmn_code = plmn_match.group(1) if plmn_match else "未知"
            
            # 提取运营商名称（PLMN前面的文本）
            carrier_match = re.search(r'(\w+).*?PLMN', row_str)
            carrier_name = carrier_match.group(1) if carrier_match else "未知运营商"
            
            current_carrier = {
                'name': carrier_name,
                'plmn': plmn_code,
                'start_row': index,
                'full_text': row_str.strip()
            }
            carriers.append(current_carrier)
            print(f"\n发现运营商分组 #{len(carriers)}:")
            print(f"  行号: {index}")
            print(f"  运营商: {carrier_name}")
            print(f"  PLMN: {plmn_code}")
            print(f"  完整文本: {row_str.strip()}")
    
    # 计算每个运营商的数据范围
    for i, carrier in enumerate(carriers):
        if i < len(carriers) - 1:
            carrier['end_row'] = carriers[i + 1]['start_row'] - 1
        else:
            carrier['end_row'] = len(df) - 1
        
        print(f"\n运营商 {carrier['name']} 数据范围: 行 {carrier['start_row']} 到 {carrier['end_row']}")
    
    # 显示每个分组的数据样本
    print("\n" + "="*60)
    print("各运营商分组数据预览:")
    
    for i, carrier in enumerate(carriers):
        print(f"\n{'-'*20} {carrier['name']} (PLMN: {carrier['plmn']}) {'-'*20}")
        
        # 找到该分组中的表头行
        header_row = None
        for row_idx in range(carrier['start_row'], min(carrier['start_row'] + 5, carrier['end_row'] + 1)):
            if row_idx < len(df):
                row_data = df.iloc[row_idx].dropna().tolist()
                if any('Search Priority' in str(cell) for cell in row_data):
                    header_row = row_idx
                    break
        
        if header_row:
            print(f"表头行: {header_row}")
            # 显示这个分组的前几条数据
            data_start = header_row + 1
            data_end = min(data_start + 3, carrier['end_row'] + 1)
            
            for data_row in range(data_start, data_end):
                if data_row < len(df):
                    row_data = df.iloc[data_row].dropna().tolist()
                    if len(row_data) > 3:  # 有实际数据
                        print(f"  数据行 {data_row}: {row_data}")
    
    return carriers

if __name__ == "__main__":
    carriers = analyze_carrier_sections("FS045W_APNList(V1.0.0).xlsx")
    print(f"\n总共发现 {len(carriers)} 个运营商分组")